package com.jianganming.lock;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * zookeeper 分布式锁实现
 */
public class LockDemo {

    public static void main(String[] args) {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000,10))
                .build();
        curatorFramework.start();
        testLock(curatorFramework);

    }

    private static void testLock(CuratorFramework curatorFramework){
        InterProcessMutex lock = new InterProcessMutex(curatorFramework,"/locks");
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    //System.out.println(Thread.currentThread().getName()+"尝试获取锁");
                    lock.acquire();
                    System.out.println(Thread.currentThread().getName()+"获取锁成功");
                    //Thread.sleep(3000);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    try {
                        lock.release();
                        System.out.println(Thread.currentThread().getName()+"释放锁成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            },"thread"+i).start();
        }
    }
}
